﻿#include "EncodeTextureMagager.h"
EncodeTextureMagager* EncodeTextureMagager::s_pEncodeTextureMagager = NULL;

EncodeTextureMagager* EncodeTextureMagager::getInstance() {
	if (s_pEncodeTextureMagager == NULL) {
		s_pEncodeTextureMagager = new EncodeTextureMagager();
	}
	return s_pEncodeTextureMagager;
}
void EncodeTextureMagager::staticFinalize() {
	CC_SAFE_DELETE(s_pEncodeTextureMagager);
}


EncodeTextureMagager::EncodeTextureMagager() {
	m_encodeTexture2dMap = std::map<std::string, cocos2d::Texture2D*>();
}

EncodeTextureMagager::~EncodeTextureMagager() {
	for (std::map<std::string, cocos2d::Texture2D*>::iterator it = m_encodeTexture2dMap.begin(); it != m_encodeTexture2dMap.end(); it++) {
		CC_SAFE_DELETE(it->second);
	}
}

cocos2d::Texture2D* EncodeTextureMagager::getEncodeTexture2d(std::string name) {
	auto fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(name);
	cocos2d::Texture2D* pTexture2D = m_encodeTexture2dMap[fullPath];
	if (pTexture2D == NULL) {
		std::vector<unsigned int> checkIndexVec;
		auto data = cocos2d::FileUtils::getInstance()->getDataFromFile(fullPath);
		for (unsigned int index = 1; index < data.getSize(); index++) {
			if (std::find(checkIndexVec.begin(), checkIndexVec.end(), index) != checkIndexVec.end()) {
				continue;
			}
			auto changeIndex = index * index;
			if (changeIndex < data.getSize()) {
				auto tempChar = data.getBytes()[index];
				data.getBytes()[index] = data.getBytes()[changeIndex];
				data.getBytes()[changeIndex] = tempChar;
				checkIndexVec.push_back(index);
				checkIndexVec.push_back(changeIndex);
			}
			else {
				break;
			}
			
		}
		unsigned char* decodeData;
		int decodeLength = cocos2d::base64Decode((const unsigned char *)data.getBytes(), data.getSize(), &decodeData);

		cocos2d::Image* img = new cocos2d::Image();
		bool ok = img->initWithImageData(decodeData, decodeLength);
		pTexture2D = new cocos2d::Texture2D();
		pTexture2D->initWithImage(img);
		CC_SAFE_DELETE(img);
		m_encodeTexture2dMap[fullPath] = pTexture2D;
	}
	return pTexture2D;
}